<template>
<div class="custom-item-container">
  <div class="new-cst-item">

    <slot name="checkerItem"></slot>
    <div class="new-info-body">
      <div class="pull-left" v-if="batchCheck === false">
        <div class="label-list baby-list clearfix" v-if="value.baby_list">
          <div class="new-info-head">
            <div  v-for="(baby, index) in value.baby_list"
                  :key="index"
                  class="cst-baby-item" :class="{
          'boy': isBoy(baby),
          'girl': !isBoy(baby)
        }">{{ getBabyTitle(baby)}}</div>
          </div>
        </div>
        <div class="new-info-tip">
          <span class="mark-ovh" v-if="value.is_member"><i class="member-mark mark-ico"></i></span>
          <span class="mark-ovh" v-if="value.is_activation"><i class="restart-mark mark-ico"></i></span>
        </div>
        <p >客户类型：{{ value.custom_property | getUserByType }}</p>
        <p>家长信息：{{ value.patriarch_name || value.parent_name }}</p>
        <p v-if="showMobile" >家长电话：{{ value.mobile_num }}</p>
        <p>来源渠道：{{ value.source || '无来源' }}<template v-if="value.second_source_name">({{value.second_source_name}})</template><template v-if="value.source">/</template>{{ value.channel }}</p>
        <p >所属顾问：{{ value.user_name }}</p>
        <p>最近跟进：{{ value.last_contact_time || value.last_care_time || '无'}}</p>
      </div>
      <div class="pull-left" v-if="batchCheck === true">
        <div class="label-list baby-list clearfix" v-if="value.baby_list">
          <div class="new-info-head">
            <div  v-for="(baby, index) in value.baby_list"
                  :key="index"
                  class="cst-baby-item" :class="{
          'boy': isBoy(baby),
          'girl': !isBoy(baby)
        }">{{ getBabyTitle(baby)}}</div>
          </div>
        </div>
        <div class="new-info-tip">
          <span class="mark-ovh" v-if="value.is_member"><i class="member-mark mark-ico"></i></span>
          <span class="mark-ovh" v-if="value.is_activation"><i class="restart-mark mark-ico"></i></span>
        </div>
        <p >客户类型：{{ value.custom_property | getUserByType }}</p>
        <p>家长信息：{{ value.patriarch_name || value.parent_name }}</p>
        <p v-if="showMobile" >家长电话：{{ value.mobile_num }}</p>
        <p>来源渠道：{{ value.source || '无来源' }}<template v-if="value.source">/</template>{{ value.channel }}</p>
        <p >所属顾问：{{ value.user_name }}</p>
        <p>最近跟进：{{ value.last_contact_time || value.last_care_time || '无'}}</p>
      </div>
      <div class="body-right" v-show="getPercentage(value)">
        <popover
        :verticalGutter="verticalGutter"
        placement="left">
          <div slot="content" class="popover-demo-content">
            {{ value.tips }}
          </div>
          <div class="c100 smallest center"

          :class="{
            ['p' + getQuitPercentage(value)] : true,
            'pink': isPink(value)
          }">
            <span
            class="percentage-text"
            ><i
              class="quit-percentage"
              :class="{
              'pink': isPink(value)
              }">{{ getPercentage(value) }}</i>{{ getPercentageText (value) }}</span>
            <div class="slice">
              <div class="bar"></div>
              <div class="fill"></div>
            </div>
          </div>
         </popover>
      </div>
    </div>
    <div class="new-info-bottom">
      <template v-if="propPosition === 'bottom'">
        <div class="prop-label"
        @click="changeProperty(YB)"
        :class="{'select': value.custom_property === 'YB#'}">一般客户</div>
        <div class="prop-label"
        @click="changeProperty(YX)"
        :class="{'select': value.custom_property === 'YX#'}">意向客户</div>
        <div class="prop-label"
        @click="changeProperty(WX)"
        :class="{'select': value.custom_property === 'WX#'}">无意向客户</div>
        <div class="prop-label"
        @click="changeProperty(NA)"
        :class="{'select': value.custom_property === 'NA#'}">无效客户</div>
      </template>
      <slot name="right">
        <div class="cst-cont" @click="jump">
          <span>查看详情</span><span class="cst-link-ico"></span>
        </div>
      </slot>
    </div>
  </div>
  <confirm v-model="propConfirm"
        title="温馨提示"
        @on-confirm="setPropConfirm">
      <p style="text-align:center;">您确定要设置该客户为无效客户吗？</p>
    </confirm>

  <x-dialog v-model="this.$store.state.app.dialogShow" >
    <div class="dialog-message">
      {{ this.$store.state.app.dialogMessage }}
    </div>
    <span class="vux-close" @click="hideDialog">知道了</span>
  </x-dialog>
</div>
</template>
<script>
const moment = require('moment')
import Vue from 'vue'
import {YB, YX, WX, NA} from '../constants/user-prop'
import { mapActions, mapState } from 'vuex'
import Q from 'q'
import Confirm from 'vux/src/components/confirm'
import Popover from '../components/popover'
import XDialog from 'vux/src/components/x-dialog'
import {showDialog, hideDialog} from '../lib/dialog'

// import Popover from 'vue-js-popover'
// Vue.use(Popover, { tooltip: true })

export default {
  props: {
    value: {
      type: Object
    },
    client: {
      type : Object,
      require: true
    },
    custom_id: {
      type: String | Number
    },
    labels: {
      type: Array
    },
    isChaChong: {
      type: Boolean,
      default: false
    },
    custom_type: {
      require:true
    },

    selectFollow: {
      default:false
    },
    isUsernameVisible: {
      default:false
    },
    showProp: {
      default: true
    },
    isEditable: {
      default: true
    },
    showMobile: {
      default: false
    },
    propPosition: {
      type: String | Number,
      default: 'bottom'
    },
    isChenJiao: {
      type: Boolean,
      default: false
    },
    verticalGutter: {
      type: Number,
      default: 0
    },
    batchCheck: {
      type: Boolean,
      default: false
    },
  },
  data () {
    return {
      YB: YB,
      YX: YX,
      WX: WX,
      NA: NA,
      labelNameStr: '',
      propConfirm: false,
      setPropConfirm: function() {},
      foo: 'myPopover'
    }
  },
  watch: {
    labels () {
      this.initLabel();
    }
  },
  components: {
    Confirm,
    Popover,
    XDialog
  },
  methods: {
    showDialog: showDialog,
    hideDialog: hideDialog,
    initLabel () {

      if (this.labels) {
        const labelNames = []
        this.labels.forEach((elem, index) => {
          labelNames.push('#' + elem.tagName + '#')
        })
        this.labelNameStr = labelNames.join(' ');
      }
    },
    changeProperty (type) {
      if (!this.isEditable) {
        return
      }

      if (this.value.custom_property === type) {
        return
      }

      if (type === WX) {
        Q.Promise((resolve, reject) => {
          this.propConfirm = true
          this.setPropConfirm = resolve
        }).then(() => {
          this.sendPropSetting(type)
        })
      } else {
        this.sendPropSetting(type)
      }
    },
    getQuitPercentage (custom) {
      if (custom.count_down_hours) {
        return Math.floor(custom.count_down_hours / (custom.total_hours  || custom.count_down_hours) * 100)
      } else if (custom.count_down_days) {
        return Math.floor(custom.count_down_days / (custom.total_days || custom.count_down_days) * 100)
      } else {
        return 0
      }
    },
    isPink (custom) {
      if (custom.count_down_hours) {
        return true
      } else {
        return false
      }
    },
    getPercentage (custom, b) {
      if (b === 'test') {
        console.log('getPercentage', custom, custom.count_down_hours, custom.count_down_days, '_', b)
      }
      if (custom.count_down_hours) {
        return custom.count_down_hours
      } else if (custom.count_down_days) {
        return custom.count_down_days
      } else {
        return false
      }
    },
    getPercentageText (custom) {
      if (custom.count_down_hours) {
        return '小时'
      } else if (custom.count_down_days) {
        return '天'
      }
    },
    sendPropSetting (type) {
      const params = {
        custom_id: this.custom_id,
        property: encodeURIComponent(type)
      }
      if (this.stop) return
      this.stop = true

      this.$vux.loading.show()

      return this.setCustomProperty(params)
        .then((response) => {
          this.$vux.loading.hide()
          if(response.data.errcode === 0){
            showDialog('设置成功!')
            const value = {
              ...this.value,
              custom_property: type
            }
            this.stop = false
            this.$emit('input', value, this.custom_id)
          } else {
            showDialog(response.data.errmsg)
          }
        }).catch(() => {
          this.stop = false
        })
    },
    isBoy (baby) {
      return baby.baby_info_str ? baby.baby_info_str.indexOf('男') > -1 : (baby.baby_sex === 'FEMALE#' ? false : true)
    },
    getBabySexStr (baby) {
      return this.isBoy(baby) ? '男' : '女'
    },
    getBabyTitle (baby) {
      const babyBirthday = baby.baby_birthday + ' 0:0:0'
      return baby.baby_info_str ? baby.baby_info_str : baby.baby_name + '（' + this.getBabySexStr(baby)+'，' + this.ages(babyBirthday) + '）'
    },
    ages (beginStr, endStr) {
      if (!beginStr) {
        return '未知年龄'
      }

      if(!endStr) {
        endStr = moment().format('YYYY-MM-DD h:mm:ss')
      }
      try {
        var reg = new RegExp(/^(\d{1,4})(-|\/)(\d{1,2})\2(\d{1,2})(\s)(\d{1,2})(:)(\d{1,2})(:{0,1})(\d{0,2})$/);
        var beginArr = beginStr.match(reg);
        var endArr = endStr.match(reg);

        var days = 0;
        var month = 0;
        var year = 0;

        days = endArr[4] - beginArr[4];
        if (days < 0) {
            month = -1;
            days = 30 + days;
        }

        month = month + (endArr[3] - beginArr[3]);
        if (month < 0) {
            year = -1;
            month = 12 + month;
        }

        year = year + (endArr[1] - beginArr[1]);

        var yearString = year > 0 ? year + "岁" : "";
        var mnthString = month > 0 ? month + "月" : "";
        var dayString = days > 0 ? days + "天" : "";

        /*
         * 1 如果岁 大于等于1 那么年龄取 几岁 2 如果 岁等于0 但是月大于1 那么如果天等于0
  天小于3天 取小时
         * 例如出生2天 就取 48小时
         */
        var result = "";
        if (year >= 1) {
            result = yearString + mnthString;
        } else {
            if (month >= 1) {
                result = days > 0 ? mnthString + dayString : mnthString;
            } else {
                var begDate = new Date(beginArr[1], beginArr[3] - 1,
                        beginArr[4], beginArr[6], beginArr[8], beginArr[10]);
                var endDate = new Date(endArr[1], endArr[3] - 1, endArr[4],
                        endArr[6], endArr[8], endArr[10]);

                var between = (endDate.getTime() - begDate.getTime()) / 1000;
                days = Math.floor(between / (24 * 3600));
                var hours = Math.floor(between / 3600 - (days * 24));
                var dayString = days > 0 ? days + "天" : "";
                result = days >= 3 ? dayString : days * 24 + hours + "小时";
            }
        }
      } catch (e) {

      }
      return result;
    } ,
    jump () {
      if (!this.$listeners || !this.$listeners.jump) {
        const value = this.value
        this.$router.push({
          path: this.selectFollow ? 'add-follow': 'normal-clients-detail',
          query:{
            custom_id: value.id,
            custom_type: this.custom_type,
            id: value.id,
            back: this.selectFollow ? 'follow-record' : false,
            dd_nav_bgcolor: 'FF5E97F6',
            action: this.isChaChong ? 'search' : '',
            isChenJiao:this.isChenJiao
          }})
      } else {
        this.$emit('jump', value)
      }
    },
    ...mapActions({
      setCustomProperty: 'setCustomProperty'
    })
  },
  beforeMount () {
    this.initLabel()
  }
}
</script>
<style lang="less">
  @import '../less/percentage-circle/less/circle.less';

  .custom-item-container {

    .popover-demo-content {
      padding: 5px 10px;
      color: #cccccc;
    }

    .body-left {
      float: left;
    }

  .pull-left {
    float: left;
  }

    .body-right {
      float: right;
      padding-top: 15px;

      .vux-popover {
        // background-color: white;
        // border: 1px solid #ccc;
      }

      .popover-content {
        color: #444;
        padding: 4px 6px;
      }
    }

    .new-cst-item {
      border-bottom: 1px solid #f3f0f0;
      margin-bottom: 10px;
      padding: 10px 0px 0px 0px;
      background-color: white;
    }

    .new-info-bottom {
      border-top: 1px solid #f3f0f0;
      padding-left: 15px;
    }
    .new-info-title {
      font-size: 16px;
      color: 444;
    }

    .cst-cont {
      padding: 10px;
      float: right;
      position: relative;

      .cst-link-ico {
        right: 0;
      }
    }

    .cst-link-ico {
      content: " ";
      display: inline-block;
      height: 6px;
      width: 6px;
      border-width: 2px 2px 0 0;
      border-color: #C8C8CD;
      border-style: solid;
      -webkit-transform: matrix(0.71, 0.71, -0.71, 0.71, 0, 0);
      transform: matrix(0.71, 0.71, -0.71, 0.71, 0, 0);
      position: relative;
      margin-top: -4px;
      right: 10px;
    }

    .new-info-tip {
      overflow: hidden;
      padding: 8px 0 0 10px;
      .mark-ovh {
        display: block;
        line-height: initial;
      }

      .mark-ico {
        display: block;
      }
    }

    .percentage-text {
      color: #444;
    }

    .quit-percentage {
      color: #01aaef;
      font-style: normal;

      &.pink {
        color: #FF6699;
      }
    }

    .new-info-body {
      overflow: hidden;
      color: #696969;
      padding-top: 8px;
      padding-bottom: 8px;
      padding-left: 15px;
      padding-right: 15px;
      min-height: 80px;
      font-size: 14px;
    }
    .new-info-body,.new-info-bottom {

    }

    .new-info-head {
      overflow: hidden;
      padding-left: 8px;
      padding-right: 15px;
    }

    .cst-baby-item {
      float: left;
      font-size: 14px;

       &.girl {
        color: #ff6698;
      }

      &.boy {
        color: #01aaef;
      }
    }

    .new-info-bottom  {
      color: #999;
      overflow: hidden;
      font-size: 12px;
    }

    .cst-info-body, .cst-info-bottom {
      color: #999999;
    }

    .cst-info-body {
      padding-bottom: 4px;
      font-size: 13px;
    }

    .prop-label {
      float: left;
      padding: 2px 10px;
      border: 1px solid #cccccc;
      margin-right: 5px;
      border-radius: 4px;
      margin-top: 7px;

      &.select {
        border: 1px solid #01aaef;
        color: #01aaef;
        position: relative;
      }

      &.select::after {
        content: '';
        width: 12px;
        height: 14px;
        right: 0;
        bottom: 0;
        z-index: 10;
        display: block;
        background: url(//fin.91mycloud.com/box-checked.png) no-repeat center center ;
        background-size: cover;
        position: absolute;
      }
    }

    div[data-popover="myPopover"] {
      font-size: 13px;
      line-height: 1.5;
      margin: 5px;
      max-width: 120px;
    }
  }
</style>
